#include"sender.h"


using namespace std;






/***************************************
			Class Sender
***************************************/


Sender::Sender()
{
	m_clock.set_mode(1000000);//单位1ms
	sender_running = true;
	server_port = 8888;
}

Sender::~Sender()
{
}


void
Sender::stop_sender()
{
	sender_running = false;
}



void
Sender::run_sender()
{
	int wsock = -1;
	int lasttime = time(0);

	wsock = udp_open();
	udp_nonblock(wsock);
	udp_connects(wsock, server_ip.c_str(), server_port);

	if(wsock<=0)
	{
		ColorPrint::printRed("Sender connect failed!\n");
		return ;
	}

	while(1)
	{
		m_clock.click();

		if(sender_running==false)
		{
			ColorPrint::printRed("sender time out!\n");
			udp_close(wsock);
			return ;
		}

		bzero(buff, sizeof(buff));

		//-------------------RECV-----------------------
		if(udp_recv(wsock, buff, sizeof(buff))>0)
		{
			//buff[sizeof(buff)-1]=0;
			printf("recv:%s\n", buff);
		}
		//--------------------SEND----------------------
		else
		{
			if(strcmp(m_clock.strTimeClicked, m_clock.strTimeClicked_last)!=0)
			{
				snprintf(data, sizeof(data), "%s", m_clock.strTimeClicked);	
				udp_send(wsock, data, strlen(data));
			}	
		}
		//usleep(1000);
	}
	udp_close(wsock);
	return ;
}



/***************************************
			Class SenderController
***************************************/

Sender *SenderController::sender_ptr	= NULL;

void
SenderController::sender_install( Sender *sender )
{
	sender_ptr = sender ;
}
void
SenderController::sender_stop_sender()
{
	sender_ptr->stop_sender();
}

/***************************************
			Class SenderThread
***************************************/
SenderThread::SenderThread()
{
}

SenderThread::~SenderThread()
{
	if(t_sender != NULL)
	{
		delete(t_sender);	
		t_sender=NULL;
	}
}

void 
SenderThread::run_independent_sender()
{
	t_sender = new thread(&Sender::run_sender, &sender);
}
void 
SenderThread::wait_for_sender()
{
	t_sender->join();
}

